package cn.iocoder.yudao.module.pay.framework.impl.weixin;

import cn.iocoder.yudao.module.api.pay.order.dto.UnifiedOrderCreateDTO;
import cn.iocoder.yudao.module.api.pay.order.eums.UnifiedPayChannelEnum;
import cn.iocoder.yudao.module.api.pay.order.eums.UnifiedPayDisplayModeEnum;
import cn.iocoder.yudao.module.api.pay.order.vo.UnifiedOrderVO;
import com.github.binarywang.wxpay.bean.order.WxPayNativeOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderV3Request;
import com.github.binarywang.wxpay.bean.result.enums.TradeTypeEnum;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import lombok.extern.slf4j.Slf4j;

/**
 * 微信支付【Native 二维码】的 PayClient 实现类
 * 文档：<a href="https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_4_1.shtml">Native 下单</a>
 *
 * @author zwy
 */
@Slf4j
public class WxNativePayClient extends AbstractWxPayClient {

    public WxNativePayClient(WxPayClientConfig config) {
        super(UnifiedPayChannelEnum.WX_NATIVE.getCode(), config);
    }

    @Override
    protected void doInit() {
        super.doInit(WxPayConstants.TradeType.NATIVE);
    }

    @Override
    protected UnifiedOrderVO doUnifiedOrderV2(UnifiedOrderCreateDTO dto) throws WxPayException {
        WxPayUnifiedOrderRequest request = buildPayUnifiedOrderRequestV2(dto)
                .setProductId(dto.getPayNo()); // V2 必须传递 productId，无需在微信配置。该参数在 V3 简化，无需传递！
        WxPayNativeOrderResult response = wxPayService.createOrder(request);
        return UnifiedOrderVO.waitingOf(UnifiedPayDisplayModeEnum.QR_CODE.getCode(), response.getCodeUrl(),
                dto.getPayNo(), "", response);
    }

    @Override
    protected UnifiedOrderVO doUnifiedOrderV3(UnifiedOrderCreateDTO dto) throws WxPayException {
        WxPayUnifiedOrderV3Request request = buildPayUnifiedOrderRequestV3(dto);
        String response = wxPayService.createOrderV3(TradeTypeEnum.NATIVE, request);
        return UnifiedOrderVO.waitingOf(UnifiedPayDisplayModeEnum.QR_CODE.getCode(), response,
                dto.getPayNo(), "", response);
    }

}
